#include <stdio.h>
#include <string.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define N 32

int main(int argc, char const *argv[])
{   
    int sockfd = -1, acceptfd = -1;
    struct sockaddr_in servaddr, clientaddr;
    socklen_t addrlen = sizeof(servaddr);
    char buf[N] ={0};

    sockfd = socket(AF_INET, SOCK_STREAM, 0); //创建网络套接字
    if (sockfd < 0){
        printf("socket failed\n");
        return -1;
    }

    memset(&servaddr, 0, addrlen);
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //将点分十进制的ip地址转化成网络字节序的无符号的32位整形数据
    servaddr.sin_port = htons(8888); //将主机字节序转化成网络字节序

    if(bind(sockfd, (struct sockaddr*)&servaddr,addrlen) == -1){ //将套接字和ipv4的网络信息结构体绑定
        printf("bind failed\n");
        return -1;
    }

    if(listen(sockfd, 5) == -1){ //将套接字变为被动监听状态，用于接收将要到来的连接请求
        printf("listen failed\n");
        return -1;
    }

    acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen); //阻塞获取等待队列中第一个连接请求
    if (acceptfd == -1){
        printf("accept failed\n");
        return -1;
    }

    int ret = -1;
    while(1){
        if((ret = recv(acceptfd, buf, sizeof(buf), 0)) < 0){ //从Socket中接收数据
            printf("recv failed\n");
            return -1;
        }else if (ret == 0){
            printf("client is quit\n");
            break;
        }

        printf("buf = %s\n",buf);
    }
    close(sockfd);
    close(acceptfd);
    return 0;
}
